package com.wondertek.common.util.trace;


import cn.hutool.core.util.RandomUtil;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.MDC;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import java.io.IOException;


@SuppressWarnings("all")
@Component
public class TraceIdFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
                                    FilterChain filterChain) throws ServletException, IOException {
        try {
            String traceId = "TR"+RandomUtil.randomNumbers(8).toUpperCase();
            MDC.put("traceId",traceId);
            filterChain.doFilter(request,response);
        }finally {
            MDC.remove("traceId");
        }
    }

}
